package com.ry.widget;

/**
 * Create by renxianzuo on 2020/12/2
 * Describe
 */

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.util.Log;

import androidx.annotation.Nullable;

/**
 * 上下文字渐变
 *
 * Create by renxianzuo on 2020/1/8
 * Describe
 */
public class MyGradientTextView extends androidx.appcompat.widget.AppCompatTextView {
    private Paint mDefaultPaint = new Paint();
    /**
     * 是否渐变
     */
    private boolean isGradient = true;

    public void setGradient(boolean gradient) {
        isGradient = gradient;
        invalidate();
    }
    public MyGradientTextView(Context context) {
        super(context);
        initPaint(context);
    }

    public MyGradientTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initPaint(context);
    }

    public MyGradientTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint(context);
    }

    private void initPaint(Context context) {
        mDefaultPaint.setAntiAlias(true);
        mDefaultPaint.setStyle(Paint.Style.FILL);
//        mDefaultPaint.setColor(0x48FFFFFF);
//        mDefaultPaint.setColor(Color.BLUE);
//        mDefaultPaint.setStrokeWidth(dipToPx(context,1f));
    }

    @Override
    protected void onLayout(boolean changed,
                            int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
            linearGradient = new LinearGradient(0,0,0,getHeight()/2,
                    new int[]{0x00ffffff,0x10ffffff,0xffffffff},new float[]{0,0.3f,1}, Shader.TileMode.CLAMP);
//            getPaint().setShader(linearGradient);
        }
    }
    LinearGradient linearGradient;
    Matrix matrix = new Matrix();

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        linearGradient.setLocalMatrix(matrix);
    }

    @Override
    protected void onScrollChanged(int horiz, int vert, int oldHoriz, int oldVert) {
        super.onScrollChanged(horiz, vert, oldHoriz, oldVert);
        Log.d("AAAAA","onScrollChanged("+horiz+","+vert+","+oldHoriz+","+oldVert+")");
        matrix.setTranslate(0,vert);
    }

    /**
     * dp转px
     *
     * @param context context
     * @param dpValue dp
     * @return px
     */
    private static int dipToPx(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
